<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class LangClassLesson extends \app\common\model\LangClassLesson
{
    /**
     * 通过班级id 和 班级类型 查找第一节课的id
     * @param $classId
     * @param $type
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getFirst($classId, $type)
    {
        return static::field('id')->where([
            'class_id' => $classId,
            'type' => $type,
            'status' => StatusEnum::ENABLED
        ])->order(['lesson' => 'ASC'])->find();
    }

    /**
     * 获取节课列表
     * @param int $classId 班级ID
     * @param int $type 类型 视频1，音频2，学习资料课件下载3，学习资料随堂作业4
     * @param int $page 页数
     * @param int $size 每页条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getList($classId, $type, $page, $size)
    {
        $offset = ($page - 1) * $size;
        $where = [
            'class_id' => $classId,
            'type' => $type,
            'status' => StatusEnum::ENABLED,
        ];
        $model = static::field('id AS lessonId, lesson, name')
            ->where($where)
            ->order(['lesson' => 'ASC'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        $count = static::where($where)->count();
        return [
            'list' => $model,
            'count' => $count
        ];
    }

    /**
     * 获取班级下面所有的节课 类型 => 数据
     * @param $classId
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getListAll($classId)
    {
        $where = [
            'class_id' => $classId,
            'status' => StatusEnum::ENABLED,
        ];
        $model = static::field('id, type, lesson, name')
            ->where($where)
            ->order(['lesson' => 'ASC'])
            ->select()
            ->toArray();

        $result = [];
        foreach ($model as $key => $value) {
            $result[$value['type']] = [
                'type' => $value['type'],
                'name' => self::attributes('type', $value['type']),
                'lessons' => [
                    'lessonId' => $value['id'],
                    'name' => $value['lesson'],
                ]
            ];
        }
        // 键从0开始
        return array_values($result);
    }

    /**
     * 通过lessonId查找对应的班级
     * @param $lessonId
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getClass($lessonId)
    {
        return static::field('class_id')
            ->where(['id' => $lessonId, 'status' => StatusEnum::ENABLED])
            ->find();
    }
}